using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.ApplicationPages;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace MOSS.CustomAdminPages.UserMembership.UI
{
    public class EditUMPage : WebAdminPageBase
    {
        #region Constructor
        public EditUMPage()
        {

        }
        #endregion

        #region Variables

        protected Button btok;
        protected Button btcancel;
        protected InputFormCheckBoxList cblUserMembership;
        protected Label lblUserLogin;
        protected TextBox txtUserLogin;
        protected Label lblError;
        private const string LISTVIEWPAGE = "ViewUMList.aspx";
        #endregion

        #region Methods / Properties

        protected override void OnLoad(EventArgs e)
        {
            ClearErrorBox();

            base.OnLoad(e);
            if (!this.IsPostBack)
            {
                string userLogin = Request.QueryString["login"] != null ? Request.QueryString["login"].ToString() : null;

                if (string.IsNullOrEmpty(userLogin))
                {
                    lblUserLogin.Visible = false;
                    txtUserLogin.Text = "";
                    txtUserLogin.Visible = true;
                }
                else
                {
                    txtUserLogin.Visible = false;
                    lblUserLogin.Text = userLogin;
                    lblUserLogin.Visible = true;
                }

                
                SPWeb web = SPContext.Current.Web;
                string groupName = null;
                if (web.CurrentUser.OwnedGroups.Count > 0 || web.CurrentUser.IsSiteAdmin)
                {
                    SPGroupCollection groups = null;
                    if (web.CurrentUser.IsSiteAdmin)
                        groups = web.SiteGroups;
                    else
                        groups = web.CurrentUser.OwnedGroups;

                    foreach (SPGroup group in groups)
                    {
                        groupName = group.Name;
                        if (!string.IsNullOrEmpty(group.Description))
                            groupName = string.Concat(groupName, " - ", group.Description);
                        ListItem item = new ListItem(groupName, group.Name);
                        if (!string.IsNullOrEmpty(userLogin))
                        {
                            SPUser user = web.SiteUsers[userLogin];
                            if (user == null)
                                throw new ApplicationException("User login is not a SharePoint user. Please check login name digits.");

                            List<string> userGroups = GetUserGroups(user);

                            if (userGroups.Contains(group.Name))
                                item.Selected = true;
                        }
                        this.cblUserMembership.Items.Add(item);
                    }
                }
                else
                {
                    ShowError("Current user is not owner of any groups.");
                    btok.Enabled = false;
                }
            }
        }

        protected void HandleOKButtonClick(object sender, EventArgs e)
        {
            ClearErrorBox();

            if (string.IsNullOrEmpty(txtUserLogin.Text) && 
                string.IsNullOrEmpty(lblUserLogin.Text))
                throw new ApplicationException("Missing user login");

            string userLogin = GetUserLogin();

            SPWeb web = SPContext.Current.Web;
            SPUser user = web.SiteUsers[userLogin];
            if (user == null)
                throw new ApplicationException("User login is not a SharePoint user. Please check login name digits.");

            List<string> userGroups = GetUserGroups(user);

            StringBuilder sbError = new StringBuilder();
            SPGroup group = null;
            bool errorGenerated = false;
            foreach (ListItem item in cblUserMembership.Items)
            {
                try
                {
                    group = web.SiteGroups[item.Value];
                    if (group != null)
                    {
                        if (item.Selected)
                        {
                            group.AddUser(user);
                            group.Update();
                        }
                        else
                        {
                            if (userGroups.Contains(group.Name))
                            {
                                group.RemoveUser(user);
                                group.Update();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (group != null)
                    {
                        sbError.AppendFormat("Exception working on group '{0}'. The error is: {1}.",
                            group.Name,
                            ex.Message);
                    }
                    else
                    {
                        sbError.AppendFormat("Exception on flow. The error is: {1}.",
                            ex.Message);
                    }
                    sbError.Append(Environment.NewLine);
                    errorGenerated = true;
                }
            }

            // Redirect to the site's settings page.
            if (!errorGenerated)
            {
                string url = LISTVIEWPAGE + "?login=" + userLogin;
                SPUtility.Redirect(url, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
            }
            else
            {
                ShowError(sbError.ToString());
            }
        }

        protected void HandleCancelButtonClick(object sender, EventArgs e)
        {
            string userLogin = GetUserLogin();

            string url = LISTVIEWPAGE + (string.IsNullOrEmpty(userLogin)?string.Empty:"?login=" + userLogin);
            SPUtility.Redirect(url, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
        }
        #endregion

        #region Private methods
        private string GetUserLogin()
        {
            string userLogin = "";
            if (txtUserLogin.Visible)
                userLogin = txtUserLogin.Text;
            else
                userLogin = lblUserLogin.Text;
            return userLogin;
        }

        private List<string> GetUserGroups(SPUser user)
        {
            List<string> userGroups = new List<string>();
            foreach (SPGroup group in user.Groups)
            {
                userGroups.Add(group.Name);
            }
            return userGroups;
        }

        private void ClearErrorBox()
        {
            lblError.Text = "";
        }

        private void ShowError(string message)
        {
            lblError.Text += message;
        }
        #endregion
    }
}




